package com.spring.activity;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.spring.entity.Attendance;
import com.spring.entity.AttendanceRecord;
import com.spring.gowhere.R;
import com.spring.httputils.RequestParams;
import com.spring.httputils.RestClient;
import com.spring.httputils.TextHttpResponseHandler;
import com.spring.model.ReturnKQResult;
import com.spring.tool.App;
import com.spring.util.Constant;
import com.spring.widget.DialogDatePicker;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

/**
 * 考勤查询
 *
 * @author Administrator
 */
public class QueryKQINfo extends BaseActivity {
    RestClient restClient = null;
    private String username, logintype;
    private TextView querykq, querykqendtime;
    private String strquerykq;
    private String title;
    private Button btnquery;
    int year;
    int month;
    int day;
    String starttime;
    String endtime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.querysf);
        title = getIntent().getExtras().getString("name");
        SharedPreferences userInfo = getSharedPreferences("user_info", 0);
        username = userInfo.getString("username", "");
        logintype = userInfo.getString("logintype", "");
        querykq = (TextView) findViewById(R.id.querykq);
        querykqendtime = (TextView) findViewById(R.id.querykqendtime);
        Calendar c = Calendar.getInstance();
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        day = c.get(Calendar.DAY_OF_MONTH);

        String strmonth;
        if (month < 10) {
            strmonth = "0" + month;
        } else {
            strmonth = "" + month;
        }
        String strmonth2;
        if (month < 10) {
            strmonth2 = "0" + (month + 1);
        } else {
            strmonth2 = "" + (month + 1);
        }

        String strday;
        if (day < 10) {
            strday = "0" + day;
        } else {
            strday = "" + day;
        }
        starttime = year + "-" + strmonth + "-" + strday;
        endtime = year + "-" + strmonth2 + "-" + strday;

        ImageButton imageButton = (ImageButton) findViewById(R.id.title_left_ib);
        imageButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView textView = (TextView) findViewById(R.id.title_tv);
        textView.setText(title);
        if (title != null && title.equals("考勤记录查询")) {
            querykqendtime.setVisibility(View.GONE);
        } else if (title != null && title.equals("进出门记录查询")) {
            querykqendtime.setVisibility(View.VISIBLE);
            querykq.setHint("请输入开始日期(格式如：2014-07-01)");

        }else if(title != null && title.equals("考勤流水查询")){//
            querykqendtime.setVisibility(View.GONE);
        }
        strquerykq = querykq.getText().toString();
        btnquery = (Button) findViewById(R.id.btnlogin);
        boolean islianwang = new Constant().isConnect(QueryKQINfo.this);
        if (islianwang) {
            btnquery.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    strquerykq = querykq.getText().toString();
                    if (strquerykq != null && !"".equals(strquerykq)) {
                        restClient = new RestClient(QueryKQINfo.this);
                        if (title != null && title.equals("考勤记录查询")) {
                            querykqendtime.setVisibility(View.GONE);
//							String url =App.getInstance().url+"/QueryKQInfo";
//							SendHttpData sendhttpdata = new SendHttpData(url, "1");
                            String url = App.getInstance().url + "/QueryATList";
                            SendHttpData sendhttpdata = new SendHttpData(url, "1");
                            sendhttpdata.run();
                        }else if(title != null && title.equals("考勤流水查询")){
                            querykqendtime.setVisibility(View.GONE);
//							String url =App.getInstance().url+"/QueryKQInfo";
//							SendHttpData sendhttpdata = new SendHttpData(url, "1");
                            String url = App.getInstance().url + "/QueryATList";
                            SendHttpData sendhttpdata = new SendHttpData(url, "1");
                            sendhttpdata.run();
                        }
                    } else {
                        Toast.makeText(QueryKQINfo.this, "请输入考勤月份", Toast.LENGTH_SHORT).show();
                    }
                }
            });

        }

        querykq.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                final Calendar cal = Calendar.getInstance();
                DialogDatePicker datePicker = new DialogDatePicker(QueryKQINfo.this,
                        new DatePickerDialog.OnDateSetListener() {

                            @Override
                            public void onDateSet(DatePicker view, int year,
                                                  int monthOfYear, int dayOfMonth) {
                                cal.set(Calendar.YEAR, year);
                                cal.set(Calendar.MONTH, monthOfYear);
                                cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                                SimpleDateFormat df = new SimpleDateFormat(
                                        "yyyy-MM", Locale.UK);
                                querykq.setText(df.format(cal.getTime()));
                                strquerykq = querykq.getText().toString();
                            }
                        }, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
                        cal.get(Calendar.DAY_OF_MONTH));
                datePicker.getDatePicker().setCalendarViewShown(false);
                ((ViewGroup) ((ViewGroup) datePicker.getDatePicker().getChildAt(0)).getChildAt(0)).getChildAt(2).setVisibility(View.GONE);
                Window window = datePicker.getWindow();
                window.setGravity(Gravity.CENTER);
                window.setWindowAnimations(R.style.DialogstyleLeft);
                datePicker.show();
            }
        });

    }


    class SendHttpData implements Runnable {
        String url;
        String type;

        SendHttpData(String url, String type) {
            this.url = url;
            this.type = type;
        }

        @Override
        public void run() {
            RequestParams requestparams = new RequestParams(url, "POST");
            requestparams.put("LoginAccount", username);
            requestparams.put("LoginType", logintype);
            if (title != null && title.equals("考勤记录查询")) {
                strquerykq = querykq.getText().toString();
                Log.e("TAG", "Date---" + strquerykq);
                requestparams.put("Date", strquerykq);
            }else if(title != null && title.equals("考勤流水查询")){
                strquerykq = querykq.getText().toString();
                Log.e("TAG", "Date---" + strquerykq);
                requestparams.put("Date", strquerykq);
            }
            TextHttpResponseHandler textHttpResponseHandler = new TextHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers,
                                      String responseString) {
                    // TODO Auto-generated method stub
                    Log.e("TAG", "responseString---" + responseString);
                    if (responseString != null && !"".equals(responseString)) {

                        Gson gson = new Gson();
                        AttendanceRecord mRecord = gson.fromJson(responseString, AttendanceRecord.class);
                        if (mRecord == null) {
                            Log.e("TAG", "mRecord null");
                        } else {
                            String returnMsg =mRecord.returnMsg;
                            if (TextUtils.isEmpty(returnMsg)) {
                                Log.e("TAG", "mRecord " + mRecord.ATList.size());
                                if(mRecord.RecordCount==0){
                                    Toast.makeText(QueryKQINfo.this,"无考勤记录", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                List<Attendance> ATList = mRecord.ATList;
                                if(ATList!=null && ATList.size()>0){
                                    Intent mIntent = new Intent();
                                    mIntent.setClass(QueryKQINfo.this,  AKQInfoActivity.class);

                                    Bundle bundle = new Bundle();
                                    bundle.putSerializable("table", (Serializable) ATList);
                                    mIntent.putExtras(bundle);
                                    startActivity(mIntent);
                                    Log.e("TAG", "mRecord AKQInfoActivity-----" );
                                }


                            } else {
                                Toast.makeText(QueryKQINfo.this, returnMsg, Toast.LENGTH_SHORT).show();
                            }
                        }

//                        AnalysisData(responseString);
                    }

                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      String responseString, Throwable throwable) {
                    // TODO Auto-generated method stub
                    Log.e("TAG", "responseString---" + responseString);
                    if (responseString != null && !"".equals(responseString)) {
//                        AnalysisData(responseString);
                    }

                }
            };
            try {
                restClient.post(url, requestparams, textHttpResponseHandler);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        /**
         * json数据解析
         *
         * @param strResult
         * @throws JSONException
         */
        private void AnalysisData(String strResult) {
            /**
             * 这里需要分析服务器回传的json格式数据，
             */
            JSONObject jsonObject = null;
            String returnMsg = null;
            try {
                jsonObject = new JSONObject(strResult);
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {

                if (title != null && title.equals("考勤记录查询")) {
                    if (jsonObject == null) {
                        return;
                    }

                    returnMsg = jsonObject.getString("returnMsg");

                    if (returnMsg != null && "".equals(returnMsg)) {
                        ReturnKQResult kqresult = new ReturnKQResult();
                        kqresult.setYearMonth(jsonObject.getString("YearMonth"));
                        kqresult.setNeedWorkDays(jsonObject
                                .getDouble("NeedWorkDays"));
                        kqresult.setWorkDays(jsonObject.getDouble("WorkDays"));
                        kqresult.setAbsentDays(jsonObject
                                .getDouble("AbsentDays"));
                        kqresult.setLateCount(jsonObject.getInt("LateCount"));
                        kqresult.setLateMins(jsonObject.getInt("LateMins"));
                        kqresult.setEarlyCount(jsonObject.getInt("EarlyCount"));
                        kqresult.setEarlyMins(jsonObject.getInt("EarlyMins"));

                        kqresult.setLeaveDays(jsonObject.getDouble("LeaveDays"));

                        kqresult.setOtherAbsentDays(jsonObject
                                .getDouble("OtherAbsentDays"));
                        Intent intent = new Intent(QueryKQINfo.this,
                                KQInfoActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("kqinfo", kqresult);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    } else {
                        Toast.makeText(QueryKQINfo.this, returnMsg, Toast.LENGTH_SHORT).show();
                    }
                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Toast.makeText(QueryKQINfo.this, returnMsg, Toast.LENGTH_SHORT).show();
            }
        }
    }
}
